# -*- coding:utf-8 -*-
import os
import random
import sys

import datetime
import flask_whooshalchemyplus
from flask import make_response
from flask import request
from flask import url_for
from flask.ext.admin.form import rules
from flask.ext.admin.model import BaseModelView
from jieba.analyse import ChineseAnalyzer

reload(sys)
sys.setdefaultencoding('utf-8')
from flask.ext.sqlalchemy import SQLAlchemy
from flask_admin import Admin
from flask_admin.contrib.sqla import ModelView
from flask_admin import BaseView, expose
from wtforms import TextAreaField
from wtforms.widgets import TextArea
from project_zczh import create_app


db=SQLAlchemy()

class Role(db.Model):
    __tablename__ = "roles"
    id = db.Column(db.Integer, primary_key=True)
    name=db.Column(db.String(64),nullable=False,unique=True)
    us = db.relationship('User', backref='role')

    def __repr__(self):
        return 'Role:%s' % self.name

class User(db.Model):
    __tablename__='users'
    id=db.Column(db.Integer,primary_key=True)
    name=db.Column(db.String(64),nullable=False)
    pwd=db.Column(db.String(64))
    roles_id= db.Column(db.Integer, db.ForeignKey('roles.id'))

    def __repr__(self):
        return 'User:%s' % self.name

class Content(db.Model):
    __tablename__='contents'
    id = db.Column(db.Integer,default=0)
    content = db.Column(db.BLOB,nullable=False)
    md5 = db.Column(db.String(32),primary_key=True)
    # list_=db.relationship('List_',backref='content')
    def __repr__(self):
        return 'Content:%s' % self.content

class Content_admin(db.Model):
    __tablename__='contents_admin'
    id = db.Column(db.Integer,primary_key=True)
    content_admin = db.Column(db.BLOB,nullable=False)
    # list_=db.relationship('List_',backref='content_admin')
    update_time = db.Column(db.Date)
    type_name=db.Column(db.Integer, db.ForeignKey('codes.id'))
    def __repr__(self):
        return 'Content_admin:%s' % self.content_admin

class Code(db.Model):
    __tablename__='codes'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64), nullable=False)
    list_=db.relationship('List_',backref='code')
    content_admin=db.relationship('Content_admin',backref='code')
    is_show=db.Column(db.SmallInteger,default=1)
    def __repr__(self):
        return 'Code:%s' % self.name

class List_(db.Model):

    __tablename__='list_s'
    __searchable__ = ['title']
    __analyzer__ = ChineseAnalyzer()
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(64), nullable=False)
    code_id = db.Column(db.Integer, db.ForeignKey('codes.id'))
    # md5 = db.Column(db.String(32),db.ForeignKey('contents.md5'),default=None,unique=True)
    md5 = db.Column(db.String(32))
    content_id = db.Column(db.Integer,default=0)
    update_time = db.Column(db.Date)
    abstract=db.Column(db.String(256))
    mark=db.Column(db.SmallInteger)
    url=db.Column(db.String(384))
    site=db.Column(db.String(45))

    """ toutiaocar
        toutiaofinance
        toutiaohot
    """
    def __repr__(self):
        return 'List_:%s' % self.title

class Table_show(db.Model):
    __tablename__="show_data"
    id = db.Column(db.Integer, primary_key=True)
    data_title=db.Column(db.String(128),nullable=False)
    url=db.Column(db.String(128))
    table_class_id = db.Column(db.Integer, db.ForeignKey('code_1.id'))
    mark = db.Column(db.SmallInteger)
    def __repr__(self):
        return 'Table_show:%s' % self.data_title

class Code_1(db.Model):
    __tablename__ = "code_1"
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64), nullable=False)
    table_show = db.relationship('Table_show', backref='code_1')
    is_show = db.Column(db.SmallInteger, default=1)
    def __repr__(self):
        return 'Code_1:%s' % self.name


#修该ModelView

#添加符文本编辑框
class CKTextAreaWidget(TextArea):
    def __call__(self, field, **kwargs):
        if kwargs.get('class'):
            kwargs['class'] += ' ckeditor'
        else:
            kwargs.setdefault('class', 'ckeditor')
        return super(CKTextAreaWidget, self).__call__(field, **kwargs)

class CKTextAreaField(TextAreaField):
    widget = CKTextAreaWidget()


class A(ModelView):
    can_view_details = True
    form_excluded_columns = ['content']
    column_filters = ['code','mark','update_time','content_id',]
    column_editable_list = ['code']
    form_choices = {
        'mark': [
            ('1','1'),
        ]
    }
    column_searchable_list = ['title']
    column_display_pk=('id')


class C(ModelView):
    column_filters = ['md5']
    extra_js = ['/static/ckeditor/ckeditor.js']
    form_overrides = {
        'content': CKTextAreaField,
    }

#定制视图类
class BlogModelView(ModelView):
    # can_view_details = True
    # create_modal = True
    # column_searchable_list = ['content']
    pass

class AnalyticsView(BaseView):
    @expose('/')
    def index(self):
        return self.render('admin/analytics_index.html')

app=create_app('development')
with app.app_context():
    db.init_app(app)



class BB(ModelView):

    extra_js = ['/static/ckeditor/ckeditor.js']
    form_overrides = {
        'content_admin': CKTextAreaField,
    }
    column_display_pk = ('id')
    column_filters = [
        'code', 'id', 'update_time'
    ]
    column_searchable_list = ['content_admin']

    @staticmethod
    def gen_rnd_filename():
        filename_prefix = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
        return '%s%s' % (filename_prefix, str(random.randrange(1000, 10000)))

    @expose('/ckupload/', methods=['POST', 'OPTIONS'])
    def ck_upload(self):
        """CKEditor file upload"""
        error = ''
        url = ''
        callback = request.args.get("CKEditorFuncNum")

        if request.method == 'POST' and 'upload' in request.files:
            fileobj = request.files['upload']
            fname, fext = os.path.splitext(fileobj.filename)
            rnd_name = '%s%s' % (BB.gen_rnd_filename(), fext)

            filepath = os.path.join(app.static_folder, 'upload', rnd_name)

            # 检查路径是否存在，不存在则创建
            dirname = os.path.dirname(filepath)
            if not os.path.exists(dirname):
                try:
                    os.makedirs(dirname)
                except:
                    error = 'ERROR_CREATE_DIR'
            elif not os.access(dirname, os.W_OK):
                error = 'ERROR_DIR_NOT_WRITEABLE'

            if not error:
                fileobj.save(filepath)
                url = url_for('static', filename='%s/%s' % ('upload', rnd_name))
        else:
            error = 'post error'

        res = """<script type="text/javascript">
      window.parent.CKEDITOR.tools.callFunction(%s, '%s', '%s');
    </script>""" % (callback, url, error)

        response = make_response(res)
        response.headers["Content-Type"] = "text/html"
        return response


with app.app_context():
    db.create_all()
    flask_whooshalchemyplus.init_app(app)
    flask_whooshalchemyplus.index_all(app)
    admin = Admin(app, name='主菜单', template_mode='bootstrap3')
    admin.add_view(BlogModelView(User, db.session,name='用户管理'))
    admin.add_view(BlogModelView(Role, db.session,name='角色管理'))
    admin.add_view(BlogModelView(Code, db.session,name='展示类别'))
    admin.add_view(A(List_, db.session,name='列表展示页面'))
    admin.add_view(C(Content, db.session,category='详情',name='来源于爬虫的内容'))
    admin.add_view(BB(Content_admin, db.session,category='详情',name='来源于后台管理的内容'))
    admin.add_view(BlogModelView(Table_show, db.session,name='图表展示'))
    admin.add_view(BlogModelView(Code_1, db.session,name='图表展示类型'))














